import { isIPv6, isIPv4, isIPv6v4Compatiable } from "./regexp";

function fullIPv4(ip: string): string {
  const fullip: string = ip
    .split(".")
    .map((i) => i.padStart(3, "0"))
    .join(".");
  return fullip;
}

function fullIPv6(ip: string): string {
  let fullip: string = ip
    .split(":")
    .map((i) => i.padStart(4, "0"))
    .join(":");
  fullip = fullip.replace(
    "0000:",
    new Array((39 - fullip.length) / 5).fill("0000").join(":") + ":0000:",
  );
  return fullip;
}

function fullfill(string: string): { ip: string; flag: string } {
  const str = string.trim();
  if (isIPv4(str)) return { ip: fullIPv4(str), flag: "ipv4" };
  if (isIPv6v4Compatiable(str))
    return { ip: fullIPv4(str.slice(2)), flag: "ipv6v4" };
  if (isIPv6(str)) return { ip: fullIPv6(str), flag: "ipv6" };
  return { ip: "", flag: "" };
}

/**
 * 判断是否是一个 IP 范围，"192.168.0.1-192.255.0.0"，支持 IPv6，IPv6 和 IPv4 无法比较
 * @param {string} str 字符串用来标记一段 IP 范围，格式是 [IP][分隔符，默认 -][IP]
 * @param {string} separator 默认值是 “-”
 * @returns {boolean} 返回是否是一个IP 范围，左边的 IP 小于右边的 IP
 * @example
 * isIpRange("::1-::2") // => true
 * isIpRange("::2-::2") // => false
 * isIpRange("192.168.0.1-192.168.0.2") // => true
 * isIpRange("::192.168.0.1-::192.168.0.2") // => true
 * isIpRange("::192.168.0.1-192.168.0.2") // => false, IPv4 不能和 IPv6 进行比较
 */
export function isIpRange(str: string, separator: string = "-"): boolean {
  const [start, end, redundant] = str.split(separator);
  if (redundant || !start || !end) return false;
  const startIP = fullfill(start),
    endIP = fullfill(end);
  if (startIP.flag === endIP.flag) return startIP.ip < endIP.ip;
  return false;
}
